<?php
/** 命名空间 */
namespace app\tool;
 
function data2xml($data,$key,$t='',$is_only = false)
{
	$xml 		 = '';
	if ('#' == $key){
		return  $xml;
	}elseif(!is_array($data)){
		if(strstr($key,'$')){
			$key  	 = substr($key,1);
			$data    = stripslashes($data);
			$xml	.= "{$t}<{$key}><![CDATA[{$data}]]></{$key}>\n";
		}else{
			if(is_numeric($data)){
				// $data = printf("%s",$data);
				$data = number_format($data,0,'','');
			}
			$xml	.= "{$t}<{$key}>{$data}</{$key}>\n";
		}		
	}elseif(array_keys($data) === range(0, count($data) - 1))
	{		
		$key2	 = strstr($key,'$')?substr($key,1):$key;
		if('' == $t || false == $is_only){
			$xml	.= "{$t}<{$key2}s>\n";
			foreach ($data as $data2){
				$xml.= data2xml($data2,$key,"{$t}\t");
			}    	
			$xml	.= "{$t}</{$key2}s>\n";
		}else{
			foreach ($data as $data2){
				$xml.= data2xml($data2,$key,"{$t}");
			} 
		}		
	}else
	{		
		$is_only_c 	 = 0;
		$is_only 	 = true; // 是否唯一子结节，唯一子结点就不包 
		foreach ($data as $key2=>$data2){
			if('#' != $key2){
				$is_only_c ++;
			}
		}
		if($is_only_c > 1){
			$is_only = false;
		}
		//////////////////////////////////////////////////////
		$v		 	= '';
		foreach ($data as $key2=>$data2){
			$v	.= data2xml($data2,$key2,"{$t}\t",$is_only);
		}
		if(is_array($data['#']))
		{
			$a   = '';
			foreach ($data['#'] as $key2=>$data2){
				if(is_numeric($data2)){
					// $data2 = printf("%s",$data2);
					$data2 = number_format($data2,0,'','');
				}
				$a .=" {$key2}=\"{$data2}\"";		
			}
			if($v){
				$xml .= "{$t}<{$key}{$a}>\n";
				$xml .= $v;
				$xml .= "{$t}</{$key}>\n";
			}else{
				$xml .= "{$t}<{$key}{$a} />\n";
			}			
		}else{
			if($v){
				$xml .= "{$t}<{$key}>\n";
				$xml .= $v;
				$xml .= "{$t}</{$key}>\n";
			}else{
				$xml .= "{$t}<{$key} />\n";
			}							
		}
	}
	return $xml;
}

function data2yrl($data,$name)
{
	// 得到长度
	$len_field	   = array();	
	$vs            = $data[0];
	foreach ($vs as $k=>$v){
		$cn 		   = mb_convert_encoding($name[$k],'GBK','UTF-8');
		$len_field[$k] = max(strlen($k),strlen($cn));
	}	
	foreach($data as $vs){
		foreach ($vs as $k=>$v){
			$cn 		   = mb_convert_encoding("<<\"{$v}\">>",'GBK','UTF-8');
			$len_field[$k] = max(strlen($cn),$len_field[$k]);
		}
	}
	// 得到注释
	$str_field 	   = array();
	$str_name  	   = array();
	$vs            = $data[0];
	foreach ($vs as $k=>$v){
		$str_name[]	 = str_pad(word2head($k),	$len_field[$k]);
		$str_field[] = str_pad($name[$k],		$len_field[$k]);
	}
	$str_rem	  = "\n% ".implode("\t,",$str_field)."\n% ".implode("\t,",$str_name)."\n";
	// 得到数据
	$str_yrl	  = '';
	foreach($data as $ks=>$vs){
		$str_t	  = array();
		foreach ($vs as $k=>$v){	
			if(!is_numeric($v)  
			   && $v[0] != '[' && $v[0] != '{'  
			   && $v != 'null' && $v != 'true' && $v != 'false' )
			{
				$v = "<<\"{$v}\">>";
			}elseif(is_numeric($v)){
				//$v = printf("%s",$v);
				$v = number_format($v,0,'','');
			}
			$str_t[] = str_pad($v,		 $len_field[$k]);
		}
		if(0==$ks%20){
			$str_yrl .= $str_rem;
		}
		$str_yrl .= " {".implode("\t,",$str_t)."}.\n";
	}
	return $str_yrl;
}

function word2head($word)
{
	return str_replace(' ','',ucwords(str_replace(array('_','$','.','#','[',']'),' ',$word)));
}

function php_data_read($mod,$keys)
{
	$filename 	= Dir_Data_Root."data_php/{$mod}/{$keys}.data.inc.php";
	$rs       	= null;
	if (file_exists($filename)){
		require $filename;
	}
	return $rs;
}
/**
 * 
 * @param $mod
 * @param $keys
 */
function php_data_delete($mod,$keys)
{
	$filename 	= Dir_Data_Root."data_php/{$mod}/{$keys}.data.inc.php";
	if (file_exists($filename)){
		unlink($filename);
	}
	file_put_contents($filename,'<?php '."\n\$rs=array();\n".'?>');
}

/**
 * 写
 * @param string $mod
 * @param string $keys
 * @param mix $data
 */
function php_data_write($mod,$keys,$data)
{
	$filedir    = Dir_Data_Root."data_php/{$mod}/";
	if(is_dir($filedir)){
		$ok = true;
	}
    if(!$ok && file_exists($filedir)){
    	unlink($filedir);
    }
    if(!$ok){
    	mkdir($filedir, 0777, true);
    }
    $filename	= "{$filedir}{$keys}.data.inc.php";
    $str		= var_export($data,true);
    file_put_contents($filename,'<?php '."\n\$rs={$str};\n".'?>');
}
/**
 * 把Excel2007文件读成数组
 * @param String $pFilename
 */
function excel_read($pFilename)
{
	if(!file_exists($pFilename)){
		exit("File \"{$pFilename}\" Not Found");
	}
	$xls_cache_file = Dir_PHP_Root.'www_tool/program/xls_cache/'.md5($pFilename).sha1($pFilename).'.c';
	$sheets	   		= array();
	if(file_exists($xls_cache_file) 
		&& filesize($xls_cache_file)  > 5 
		&& filemtime($xls_cache_file) > filemtime($pFilename) )
	{
		require $xls_cache_file;
	}else
	{
		$objReader = new PHPExcel_Reader_Excel2007();
		$objExcel  = $objReader->load ( $pFilename );
		foreach($objExcel ->getAllSheets() as $sheet)
		{
			$sheets[] = array('title' => $sheet->getTitle(),
							  'data'  => $sheet->toArray() );
		}
		$str = var_export($sheets,true);
		file_put_contents($xls_cache_file,'<?php  $sheets = '.$str.';?>');
	}
	return $sheets;
}
/**
 * 把数组解析成数据
 * @param String $pFilename
 */
function excel_parser($sheets,&$NAME,&$VALUE)
{
	$FIELDS		= array();	
	foreach($sheets as &$sheet)
	{
		//echo '$sheet:';
		//var_dump($sheet);
		foreach ($sheet['data'] as &$rs) 
		{
			$rs[0] 								= trim($rs[0]);	 
			//echo '$rs[0]:',$rs[0],'<br />';
			switch($rs[0])
			{
				case 'VALUE': //属性值所在行
					$_vs 	= array();
					foreach ($rs as $k => $v)
					{					
						if($k > 0 && $FIELDS[$k])
						{
							$_vs[$FIELDS[$k]] = trim($v);
						}
					}				
					$VALUE[] = $_vs;
					break;
				case 'NAME' :
					foreach ($rs as $k=>$v)
					{
						if($k > 0 && $FIELDS[$k])
						{
							$NAME[$FIELDS[$k]] = trim($v);	
						}						
					}
					break;
				case 'FIELDS':
					foreach ($rs as $k=>$v){
						$v				= trim($v);
						if($v)
						{
							$FIELDS[$k]	= strtolower($v);
						}
					};				
					break;
				default : //空行或其他
					break;
			}
		}
	}	
	//return array($NAME,$VALUE);
}
/**
 * 得到give数据元组
 * @param uint $goods_id 	物品ID
 * @param uint $count    	数量
 * @param uint $streng	  	强化等级
 * @param uint $name_color  物品名称的颜色
 * @param uint $bind		是否绑定(0:不绑定 1:绑定)
 * @param uint $expiry_type 有效期类型，0:不失效，1：秒，  2：天，请多预留几个以后会增加
 * @param uint $expiry		有效期，到期后自动消失，并发系统邮件通知
 */
function goods_give($goods_id,$count=1,$streng=0,$name_color=1,$bind=1,$expiry_type=0,$expiry=0)
{
	return "{give,{$goods_id},{$count},{$streng},{$name_color},{$bind},{$expiry_type},{$expiry}}";
}
/**
 * xml2key
 * @param $string
 */
function xml2key($string)
{
	$string	  = trim($string);
	$string	  = str_replace('[','\'][',$string);
	$string	  = str_replace(']','][\'',$string);
	$xv		  = str_replace('.','\'][\'',$string);
	if('#' == $xv[0]){
		$xv	  = '[\'#\'][\''.substr($xv,1).'\']';
	}else{
		$xv   = '[\''.str_replace('#','\'][\'#\'][\'',$xv).'\']';
	}
	$xv		  = str_replace('\'][\'[','\'][',$xv);
	$xv		  = str_replace('][\'\'][','][',$xv);
	//echo $xv,'<br />';
	return $xv;
}

function array_format($data)
{
	if(is_array($data))
	{
		if(array_keys($data) === range(0, count($data) - 1)){
			return $data;
		}else{
			return array($data);
		}
	}else{
		return array();
	}
}